import Icon from '@/components/Icon'

import styles from './index.module.scss'
import {Popup, Tabs} from "antd-mobile";
import {getUserChannel, updateActiveChannelKey} from "@/store/actions/home";
import useInitState from "@/utils/useInitState";
import Channels from "@/pages/Home/components/Channels";
import {useState} from "react";
import {useDispatch} from "react-redux";
import ArticleList from "@/pages/Home/components/ArticleList";
import {useHistory} from "react-router-dom";

// 获取频道数据的逻辑根用户是否登录强关联的
// 只要用户登陆了，我们获取的就是服务器端用户的频道数据
// 如果用没有登录
//   1、获取本地存储频道数据
//   2、如果本地存储没有数据，我也是从服务器获取默认的频道数据
const Home = () => {
  const [visible, setVisible] = useState(false);
  const dispatch = useDispatch()
  const history = useHistory()
  const {userChannel = [], activeChannelKey} = useInitState(getUserChannel, 'home')


  const onChannelChange = () => {
    setVisible(!visible)
  }

  const onTabChange = (key) => {
    dispatch(updateActiveChannelKey(key))
  }
  return (
    <div className={styles.root1}>
      {
        userChannel.length > 0 && (
          <Tabs
            activeKey={activeChannelKey + ''}
            className="tabs"
            activeLineMode="fixed"
            onChange={onTabChange}
          >
            {
              userChannel.map(item => (
                <Tabs.Tab title={item.name} key={item.id + ''}>
                  <ArticleList channelId={item.id}/>
                </Tabs.Tab>
              ))
            }
          </Tabs>
        )
      }
      <div className="tabs-opration">
        <Icon type="iconbtn_search" onClick={() => history.push('/search')}/>
        <Icon type="iconbtn_channel" onClick={onChannelChange}/>
      </div>

      <Popup
        visible={visible}
        position={'left'}
        className={"channel-popup"}
      >
        {/* 弹出层内容组件*/}
        <Channels onClose={onChannelChange}/>
      </Popup>
    </div>
  )
}

export default Home
